package com.rookie.data.generate.controller;

import com.rookie.data.generate.component.GenerateScanRegister;
import com.rookie.data.generate.constant.ResponseResult;
import com.rookie.data.generate.model.dto.MultiplyTableDTO;
import com.rookie.data.generate.model.project.DataSourceEntity;
import com.rookie.data.generate.model.project.FieldProperties;
import com.rookie.data.generate.service.SystemService;
import com.rookie.data.generate.util.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map;

/**
 * @author rookie
 */
@Slf4j
@RestController
@RequestMapping("system")
public class SystemController {

    @Autowired
    private SystemService systemService;

    /**
     * 给数据库中所有表插入随机数据
     *
     * @param times 数据条数
     * @return 操作结果
     */
    @GetMapping("insertAllTableData")
    public ResponseResult<String> insertAllTableData(Integer times) {
        return systemService.insertAllTableData(times);
    }


    /**
     * 指定表生成随机数据
     *
     * @param table 表名
     * @param times 生成数据条数
     * @return 操作结果
     */
    @GetMapping("generateData")
    public ResponseResult<String> generateData(String table, Integer times) {
        return systemService.insertData(table, times);
    }

    /**
     * 批量生成表随机数据
     *
     * @param param 参数
     * @return 操作结果
     */
    @PostMapping("insertMultiplyTableData")
    public ResponseResult<String> insertMultiplyTableData(@RequestBody MultiplyTableDTO param) {
        return systemService.insertMultiplyTableData(param);
    }


    @GetMapping("getTableConfig")
    public ResponseResult<Map<String, Map<String, FieldProperties>>> getTableConfig() {
        return ResultUtils.success(GenerateScanRegister.getAllConfig());
    }

    @GetMapping("refreshConfig")
    public ResponseResult<String> refreshConfig() {
        GenerateScanRegister.REGISTER.registerBeanDefinitions(null,null);
        return ResultUtils.success();
    }

    @GetMapping("dependentGenerate")
    public ResponseResult<String> dependentGenerate(String table, Integer times) {
        return systemService.dependentGenerate(table, times);
    }

    public Boolean checkDataSource(DataSourceEntity dataSource) {
        try {
            DriverManager.getConnection(dataSource.getUrl(), dataSource.getUserName(), dataSource.getPassword());
        } catch (SQLException e) {
            log.error("数据源配置 {} , 获取链接失败", dataSource.getName(), e);
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }
}
